//
//  DeviceSetViewController.m
//  project
//
//  Created by 圆圆陈 on 2017/12/16.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "DeviceSetViewController.h"
#import "FeedBackViewController.h"
#import "AboutAppViewController.h"
#import "TimeSetView.h"
#import "WareUpdateViewController.h"
#import "OTAUpdateFirmwareNordicVc.h"
#import "DeviceFunctionCell.h"

@interface DeviceSetViewController ()<UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>
@property(nonatomic, strong) UITableView    *tableView;
@property(nonatomic, strong) NSMutableArray *titleArr;
@property(nonatomic, strong) NSMutableArray *timeArr;
@property(nonatomic, strong) NSString       *cacheStr;
@property(nonatomic, assign) BOOL           selected;
@end

@implementation DeviceSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorHEX(0xf0f2f5);
    
    UIView *StateView = [[UIView alloc] init];
    StateView.frame           = CGRectMake(0, 0, kSCREEN_WIDTH, 20);
    StateView.backgroundColor = BBIGSTATECOLOR;
    [self.view addSubview:StateView];
    
    UIView *naView = [[UIView alloc] init];
    naView.frame           = CGRectMake(0, 20+FitSimpleIpx(0, 20), kSCREEN_WIDTH, 44);
    naView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:naView];
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20), screenWidth, 44)];
    lable.textColor     = UIColorHEX(0x161616);
    lable.font          = SNFONTMEDIUM(17);
    lable.textAlignment = NSTextAlignmentCenter;
    lable.text          = HHH_Text(@"设备设置");
    
    [self.view addSubview:lable];
    
    UIButton *leftButton = [[UIButton alloc] init];
    leftButton.frame = CGRectMake(5, 20+FitSimpleIpx(0, 20), 44, 44);
    [leftButton setImageNormal:@"进入"];
    [leftButton addTarget:self action:@selector(leftbuttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    
    UIImageView *shadowLine = [[UIImageView alloc] init];
    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44 -2, HHHWIDTH, 2);
    shadowLine.image = [UIImage image:@"lineImage"];
//    [self.view addSubview:shadowLine];
    
    _tableView                 = [[UITableView alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20)+44+10, HHHWIDTH, HHHHEIGHT-20-FitSimpleIpx(0, 20)-44-2-FitSimpleIpx(0, 34)) style:UITableViewStylePlain];
    _tableView.delegate        = self;
    _tableView.dataSource      = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    _tableView.sectionHeaderHeight = 20;
    [self.view addSubview:_tableView];
    
    [self updateOnliceDevice];
    _timeArr  = [NSMutableArray arrayWithObjects:@"", @"", nil];
    
    _cacheStr = [self getCacheSize];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateOnliceDevice) name:@"updateOnliceDevice" object:nil];
}

- (void)updateOnliceDevice
{
    _titleArr = [NSMutableArray array];
    [_titleArr addObject:SN_Text(@"手环固件更新")];
    [_titleArr addObject:SN_Text(@"关于APP1")];
    
    [_titleArr addObject:@"空的"];
    
    NSLog(@"是否支持心率>>>%i",SN_USER.heart);
    if (SN_USER.heart) {
        [_titleArr addObject:SN_Text(@"心率自动检测")];
    }
    
    [_titleArr addObject:SN_Text(@"抬腕亮屏")];
    if (SN_USER.showBleLost) {
        [_titleArr addObject:SN_Text(@"防丢提醒")];
    }
    else
    {
        
    }
    [_titleArr addObject:SN_Text(@"恢复手环出厂设置")];
    [_titleArr addObject:SN_Text(@"解除设备绑定")];
    [_tableView reloadData];
}

- (void)leftbuttonClick {
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString *)getCacheSize {
    //定义变量存储总的缓存大小
    long long sumSize = 0;
    
    //01.获取当前图片缓存路径
    NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    
    //02.创建文件管理对象
    NSFileManager *filemanager = [NSFileManager defaultManager];
    
    //获取当前缓存路径下的所有子路径
    NSArray *subPaths = [filemanager subpathsOfDirectoryAtPath:cacheFilePath error:nil];
    
    //遍历所有子文件
    for (NSString *subPath in subPaths) {
        //1）.拼接完整路径
        NSString *filePath = [cacheFilePath stringByAppendingFormat:@"/%@", subPath];
        //2）.计算文件的大小
        long long fileSize = [[filemanager attributesOfItemAtPath:filePath error:nil]fileSize];
        //3）.加载到文件的大小
        sumSize += fileSize;
    }
    float size_m = sumSize/(1000*1000);
    return size_m < 1 ? @"" : [NSString stringWithFormat:@"%.2fM", size_m];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _titleArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 2) {
        return 20;
    }
    return  50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"deviceFunctionCell";
    DeviceFunctionCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (nil == cell) {
        cell = [[DeviceFunctionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSString *title = _titleArr[indexPath.row];
    CGFloat height = 50;

    if (indexPath.row == 2) {
        cell.backgroundColor = UIColorHEX(0xf0f2f5);
        UIView *linev = [[UIView alloc] initWithFrame:SNFRAME(20, 10, screenWidth-40, 0.5)];
        linev.backgroundColor = UIColorHEX(0xd9d9d9);
        [cell addSubview:linev];
    }
    else
    {
        [cell updateCellWithModel:title withHeight:height];
    }
    
    if ([title isEqualToString:SN_Text(@"手环固件更新")]||[title isEqualToString:SN_Text(@"关于APP1")]||[title isEqualToString:SN_Text(@"恢复手环出厂设置")]||[title isEqualToString:SN_Text(@"解除设备绑定")]) {
        UIView *tempView1 = [[UIView alloc] initWithFrame:cell.frame];
        tempView1.backgroundColor   = [UIColor lightTextColor];
        cell.selectedBackgroundView = tempView1;
    }

    if ([title isEqualToString:SN_Text(@"心率自动检测")]) {
        ZJSwitch *btn = [[ZJSwitch alloc] initWithFrame:CGRectMake(HHHWIDTH-50, FitH(10), 50, 22)];
        btn.tag = 102;
        [cell addSubview:btn];
        btn.on = SN_USER.heartAutoCheck;
        cell.accessoryView = btn;
        [btn addTarget:self action:@selector(handleSwitchEvent:) forControlEvents:UIControlEventValueChanged];
    }
    if ([title isEqualToString:SN_Text(@"抬腕亮屏")]) {
        ZJSwitch *btn = [[ZJSwitch alloc] initWithFrame:CGRectMake(HHHWIDTH-50, FitH(10), 50, 22)];
        btn.tag = 103;
        [cell addSubview:btn];
        btn.on = SN_USER.liftNotice;
        if (KK_BLEModel.bleAdvID==3089 || KK_BLEModel.bleAdvID==1821|| KK_BLEModel.bleAdvID==11805|| KK_BLEModel.bleAdvID==23581) {
            cell.detailTextLabel.text = SN_Text(@"该功能请在手环上设置");
            btn.enabled = NO;
        }
        else
        {
            btn.enabled = YES;
        }
        cell.accessoryView = btn;
        [btn addTarget:self action:@selector(handleSwitchEvent:) forControlEvents:UIControlEventValueChanged];
        
    }
    if ([title isEqualToString:SN_Text(@"防丢提醒")]) {
        ZJSwitch *btn = [[ZJSwitch alloc] initWithFrame:CGRectMake(HHHWIDTH-50, FitH(10), 50, 22)];
        btn.tag = 104;
        [cell addSubview:btn];
        btn.on = SN_USER.lostNotice;
        cell.accessoryView = btn;
        [btn addTarget:self action:@selector(handleSwitchEvent:) forControlEvents:UIControlEventValueChanged];
        
    }
    return cell;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SN_Net getDeviceUpdateInfoFromServerWithSuccess:^(id object) {
        if (KK_BLEModel.bleOnlineVersion > KK_BLEModel.bleVersion) {
        } else {
        }
    } fail:^(id object) {
    }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"updateOnliceDevice" object:nil];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *title = _titleArr[indexPath.row];
    if (_selected == NO) {
        if ([title isEqualToString:SN_Text(@"手环固件更新")]) {
            _selected = YES;
            NSLog(@"KK_BLEModel.batteryQuantity>>>%d",KK_BLEModel.batteryQuantity);
            if (KK_BLEModel.batteryQuantity < 20) {
                SHOWMBProgressHUD(nil, SN_Text(@"电量不足,请充电后再升级"), nil, NO, 2.0);
                _selected = NO;
                return;
            }
            if (KK_BLEModel.bleOnlineVersion > KK_BLEModel.bleVersion) {
                NSLog(@"KK_BLEModel.chip>>>>%@",KK_BLEModel.chip);
                if ([KK_BLEModel.chip containsString:@"nrf"]) {
                    OTAUpdateFirmwareNordicVc *vc = [[OTAUpdateFirmwareNordicVc alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                } else if ([KK_BLEModel.chip containsString:@"da"]) {
                } else if ([KK_BLEModel.chip containsString:@"syd"]) {
                    OTAUpdateFirmwareNordicVc *vc = [[OTAUpdateFirmwareNordicVc alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
                else if([KK_BLEModel.chip containsString:[@"PHY" lowercaseString]])
                {
                    OTAUpdateFirmwareNordicVc *vc = [[OTAUpdateFirmwareNordicVc alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
                KK_BLEConnect.fwxOta = NO;
            } else {
                SHOWMBProgressHUD(nil, SN_Text(@"当前已为最新版本"), nil, NO, 2.0);
            }
        }
        if ([title isEqualToString:SN_Text(@"关于APP1")]) {
            AboutAppViewController *appVC = [[AboutAppViewController alloc]init];
            [self.navigationController pushViewController:appVC animated:YES];
        }
        
        _selected = NO;
        if ([title isEqualToString:SN_Text(@"恢复手环出厂设置")]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"是否确定？")
                                                            message:SN_Text(@"我们即将清除你手环的所有设置与数据，且无法恢复，确定恢复设备的出厂设置？") delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:SN_Text(@"取消"), SN_Text(@"确定"), nil];
            [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
            alert.tag = 105;
            [alert show];
        }
        if ([title isEqualToString:SN_Text(@"解除设备绑定")]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"是否确定？")
                                                            message:SN_Text(@"解除APP与设备的绑定后，您的设备将无法继续接收来自APP的信息提醒和电话管理等功能（部分设备无此功能），是否要继续？") delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:SN_Text(@"取消"), SN_Text(@"确定"), nil];
//#FF7A00
            [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
            alert.tag = 107;
            [alert show];
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        if (alertView.tag == 105) {
            [KK_BLESend sendDeviceRebootWithUpdate:^(id object, KKBLEAcceptType type) {
            }];
        } else if (alertView.tag == 106) {
            NSFileManager *fileManager = [NSFileManager defaultManager];
            
            NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
            
            [fileManager removeItemAtPath:cacheFilePath error:nil];
        } else if (alertView.tag == 107) {
            [@"ScreenViewXy" setObjectValue:nil];
            NSString *path_sandox = NSHomeDirectory();
            //设置一个图片的存储路径
            NSString *imagePath = [path_sandox stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@.png", KK_BLEModel.bleMAC]];
            NSFileManager *fileManger = [NSFileManager  defaultManager];//文件管理器
             [fileManger removeItemAtPath:imagePath error:nil];
            
            [KK_BLEConnect exPairDevice];
            SN_PublicClass.todaySleepArray = [NSMutableArray array];
            SN_PublicClass.yesSleepArray = [NSMutableArray array];
            
            [SN_Net updateBleDevice:RemoveEquipment Success:^(id object) {
                SHOWMBProgressHUD(SN_Text(@"解绑成功"), nil, nil, NO, 2.0);
                [self.navigationController popViewControllerAnimated:NO];
            } fail:^(id object) {
                SHOWMBProgressHUD(SN_Text(@"解绑失败"), nil, nil, NO, 2.0);
            }];
        }
    }
}

- (void)setBtnClick:(UIButton *)sender {
    TimeSetView *setView = [[TimeSetView alloc]initWithFrame:self.view.bounds withType:sender.tag == 100 ? HeartAuto : TwistLight];
    
    [self.view addSubview:setView];
    [setView animationUp];
    setView.sureButtonBlock = ^(NSString *str) {
        if (sender.tag == 103) {
            [_timeArr replaceObjectAtIndex:0 withObject:str];
        } else {
            [_timeArr replaceObjectAtIndex:1 withObject:str];
        }
        [_tableView reloadData];
    };
}

- (void)handleSwitchEvent:(ZJSwitch *)sender {
    NSLog(@"sender tag>>>%d   !! %i", sender.tag, sender.on);
    if (sender.tag == 102) {
        SN_USER.heartAutoCheck = sender.on;
    } else if (sender.tag == 103) {
        SN_USER.liftNotice = sender.on;
    } else {
        SN_USER.lostNotice = sender.on;
    }
    [SN_USER updateToDB];
    [SN_EveryDayModelHelp startUpdateSettingOther];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

